﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SaleDiscount.Data.CollectionClasses;
using SaleDiscount.Data.EntityClasses;
using SaleDiscount.Data.HelperClasses;
using SaleDiscount.Portal.Common;
using NetDon.Utilities;
using SaleDiscount.Portal.Service;
using SaleDiscount.Portal.eBay;
using eBay.Service.Call;
using eBay.Service.Core.Soap;

namespace SaleDiscount.Portal
{
    public partial class SaleDiscountEdit : SaleDiscountPageBase
    {
        private SaleEntity entity;
        private ItemIDArrayType newItemArray;
        private ItemIDArrayType removedItemArray;
        #region Properties
        protected int Id
        {
            get
            {
                return Parameters.GetInt32("Id");
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            hyperLinkSelectListings.Attributes.Add("onclick", "chooseListings();return false;");
            hyperLinkClearListings.Attributes.Add("onclick", "clearListings();return false;");



            if (!IsPostBack)
            {
                txtStartDate.Text = DateTime.Now.ToString("MM/dd/yyyy");

                txtEndDate.Text = DateTime.Now.AddDays(1).ToString("MM/dd/yyyy");
                BindDropDownLists();

                this.txtStartDateHour.SelectedValue = DateTime.Now.Hour.ToString().PadLeft(2, '0');
                this.txtStartDateMinute.SelectedValue = DateTime.Now.Minute.ToString().PadLeft(2, '0');

                this.txtEndDateHour.SelectedValue = DateTime.Now.Hour.ToString().PadLeft(2, '0');
                this.txtEndDateMinute.SelectedValue = DateTime.Now.Minute.ToString().PadLeft(2, '0');
                this.radioDiscountRatio.Checked = true;
                this.CheckBoxAddAllActiveAuctionListings.Enabled = false;

                panelForModify.Visible = Id>0;
                panelForAdd.Visible = !(Id>0);
                CancelButton = btnReturn;

                if (Id > 0)
                {

                    var saleEntity = new SaleEntity();
                    saleEntity.FetchUsingPK(Id);
                    panelCustomInfo.DataSource = saleEntity;
                    panelCustomInfo.DataBind();
                    //
                    this.txtStartDateHour.Text = saleEntity.StartDate.Hour.ToString();
                    this.txtStartDateMinute.Text = saleEntity.StartDate.Minute.ToString();

                    this.txtEndDateHour.Text = saleEntity.EndDate.Hour.ToString();
                    this.txtEndDateMinute.Text = saleEntity.EndDate.Minute.ToString();

                    this.ckbIsAuctionExcluded.Checked = saleEntity.IsAuctionExcluded;
                    if (!ckbIsAuctionExcluded.Checked)
                    {
                        this.CheckBoxAddAllActiveAuctionListings.Enabled = true;
                    }
                    this.radioDiscountRatio.Checked = saleEntity.DiscountType == (short)DiscountType.ByRatio;
                    this.radioDiscountAmount.Checked = saleEntity.DiscountType == (short)DiscountType.Fixed;
                    if (radioDiscountAmount.Checked)
                    {
                        txtDiscount.Text = saleEntity.DiscountRatio.ToString();
                    }
                    else
                    {
                        txtDiscountRatio.Text = saleEntity.DiscountRatio.ToString();
                    }
                    this.CheckBoxAddAllActiveAuctionListings.Checked = saleEntity.AllAuctionItems;
                    this.CheckBoxAddAllActiveFixedPriceListings.Checked = saleEntity.AllFixedPriceItems;
                    this.CheckBoxAddAllListingsFromCategory.Checked = saleEntity.AllStoreInventoryItems;
                    this.ckbIsFreeshipping.Checked = saleEntity.IsFreeShipping;
                    if (saleEntity.StoreCatetoryId.HasValue)
                        this.ddlStoreCategory.SelectedValue = saleEntity.StoreCatetoryId.Value.ToString();

                    this.hyperLinkClearListings.Visible = false;
                    spanSeperator.Visible = false;
                    if (saleEntity.SaleListings.Any())
                    {
                        spanSeperator.Visible = true;
                        hyperLinkClearListings.Visible = true;
                        fieldListingIds.Value =
    saleEntity.SaleListings.Select(o => o.ItemId.ToString()).Aggregate((a, b) => a + "," + b);
                    }

                    if (GetStatus(saleEntity.StartDate, saleEntity.EndDate) == "Active")
                    {
                        txtStartDate.Enabled =
                            txtStartDateHour.Enabled =
                            txtStartDateMinute.Enabled =
                            txtEndDate.Enabled = txtEndDateHour.Enabled = txtEndDateMinute.Enabled = false;
                        ckbIsAuctionExcluded.Enabled =
                            radioDiscountAmount.Enabled =
                            radioDiscountRatio.Enabled = txtDiscount.Enabled = txtDiscountRatio.Enabled = false;
                    }

                    ChangeDiscountValidations();

                }

            }
        }



        private void BindDropDownLists()
        {
            LoadStoreCategories();
            LoadHourAndMinutes();

        }

        protected void ckbIsAuctionExcluded_CheckedChanged(object sender, EventArgs e)
        {
            this.CheckBoxAddAllActiveAuctionListings.Enabled = !ckbIsAuctionExcluded.Checked;
        }

        protected void radioDiscountRatio_CheckedChanged(object sender, EventArgs e)
        {
            ChangeDiscountValidations();
        }


        private void ChangeDiscountValidations()
        {
                RequiredFieldValidatorDiscountRatio.Enabled = NumericEditExtenderDiscountRatio.Enabled = this.radioDiscountRatio.Checked;
                RequiredFieldValidatorDiscount.Enabled = NumericEditExtenderDiscount.Enabled = this.radioDiscountAmount.Checked;
          
        }
        private void LoadHourAndMinutes()
        {
            for (int i = 0; i < 24; i++)
            {
                txtStartDateHour.Items.Add(i.ToString().PadLeft(2, '0'));
                txtEndDateHour.Items.Add(i.ToString().PadLeft(2, '0'));
            }

            for (int i = 0; i < 60; i++)
            {
                txtStartDateMinute.Items.Add(i.ToString().PadLeft(2, '0'));
                txtEndDateMinute.Items.Add(i.ToString().PadLeft(2, '0'));
            }
        }


        private void LoadStoreCategories()
        {

            if (StoreCategories != null)
            {
                foreach (StoreCustomCategoryType storeCategory in StoreCategories)
                {
                    ddlStoreCategory.Items.Add(new ListItem(storeCategory.Name, storeCategory.CategoryID.ToString()));
                }
            }
            ddlStoreCategory.Items.Insert(0, new ListItem("Select a category", string.Empty));
        }



        private bool CreateSale()
        {

            if (Save())
            {


                var promationSale = new PromotionalSaleType();
                promationSale.PromotionalSaleName = entity.SaleName;
                promationSale.PromotionalSaleStartTime = entity.StartDate;
                promationSale.PromotionalSaleEndTime = entity.EndDate;
                promationSale.DiscountType = entity.DiscountType == (int)DiscountType.ByRatio
                    ? DiscountCodeType.Percentage
                    : DiscountCodeType.Price;
                promationSale.DiscountValue = Convert.ToDouble(entity.DiscountRatio);
                if (entity.IsAuctionExcluded && entity.IsFreeShipping)
                {
                    promationSale.PromotionalSaleType1 = PromotionalSaleTypeCodeType.PriceDiscountAndFreeShipping;
                }
                else if (entity.IsFreeShipping)
                {
                    promationSale.PromotionalSaleType1 = PromotionalSaleTypeCodeType.FreeShippingOnly;
                }
                else if (entity.IsAuctionExcluded)
                {
                    promationSale.PromotionalSaleType1 = PromotionalSaleTypeCodeType.PriceDiscountOnly;
                }
                PromotionalSaleStatusCodeType result = PromotionalSaleStatusCodeType.Active;

                //promotionId
                if (entity.PromotionSaleId.HasValue)
                {
                    promationSale.PromotionalSaleID = entity.PromotionSaleId.Value;
                    result = new eBaySession().SetPromotionalSale(ModifyActionCodeType.Update, promationSale);
                }
                else
                {
                    result = new eBaySession().SetPromotionalSale(ModifyActionCodeType.Add, promationSale);
                }

                //update listings

                new eBaySession().SetPromotionalSaleListings(
                    promationSale.PromotionalSaleID, ModifyActionCodeType.Add, newItemArray,
                    string.IsNullOrWhiteSpace(ddlStoreCategory.SelectedValue)
                        ? 0
                        : (long)ddlStoreCategory.SelectedValue.ToDouble(), 0, entity.AllFixedPriceItems,
                    entity.AllStoreInventoryItems, entity.AllAuctionItems);

                if (removedItemArray.ItemID.Count > 0)
                {
                    new eBaySession().RemovePromotionalSaleListings(
                      promationSale.PromotionalSaleID, removedItemArray);
                }


                entity.PromotionSaleId = promationSale.PromotionalSaleID;
                entity.Status = result.ToString();
                entity.Save();
                return true;
            }

            return false;

        }

        private ItemIDArrayType GetItemArray()
        {
            var items = new ItemIDArrayType();
            items.ItemID = new StringCollection();
            if (!string.IsNullOrWhiteSpace(fieldListingIds.Value))
            {
                items.ItemID.AddRange(fieldListingIds.Value.Split(new char[] { ',' }));
            }
            return items;
        }

        private bool Save()
        {
            //validate

            var trans = new Transaction(IsolationLevel.ReadCommitted, "RemoveSaleDiscount");
            try
            {
                if (Id > 0)
                {
                    entity = new SaleEntity(Id);

                }
                else
                {
                    entity = new SaleEntity();
                }
                entity.EBayUserTokenId = EbayUserTokenId.Value;
                entity.SaleName = txtSaleName.Text.Trim();

                DateTime? dateStart = null, dateEnd = null;
                if (!string.IsNullOrEmpty(txtStartDate.Text.Trim()))
                {
                    dateStart = DateTime.Parse(txtStartDate.Text.Trim());
                }
                if (!string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                {
                    dateEnd = DateTime.Parse(txtEndDate.Text.Trim());
                }
                if (dateStart.HasValue)
                {
                    var startHour = Convert.ToDouble(txtStartDateHour.SelectedValue);
                    var startMinute = Convert.ToDouble(txtStartDateMinute.SelectedValue);
                    entity.StartDate = dateStart.Value.AddHours(startHour).AddMinutes(startMinute);
                }
                if (dateEnd.HasValue)
                {
                    var endHour = Convert.ToDouble(txtEndDateHour.SelectedValue);
                    var endMinute = Convert.ToDouble(txtEndDateMinute.SelectedValue);
                    entity.EndDate = dateEnd.Value.AddHours(endHour).AddMinutes(endMinute);
                }
                entity.IsAuctionExcluded = ckbIsAuctionExcluded.Checked;
                entity.DiscountRatio = radioDiscountAmount.Checked
                                           ? txtDiscount.Text.ToDecimal() ?? 0
                                           : txtDiscountRatio.Text.ToDecimal() ?? 0;
                entity.DiscountType = radioDiscountAmount.Checked ? (short)DiscountType.Fixed : (short)DiscountType.ByRatio;
                entity.IsFreeShipping = ckbIsFreeshipping.Checked;
                entity.AllAuctionItems = CheckBoxAddAllActiveAuctionListings.Checked;
                entity.AllFixedPriceItems = CheckBoxAddAllActiveFixedPriceListings.Checked;
                entity.AllStoreInventoryItems = CheckBoxAddAllListingsFromCategory.Checked;
                entity.StoreCatetoryId = ddlStoreCategory.SelectedValue.ToInt32();
                entity.CreatedDate = entity.UpdatedDate = DateTime.Now;
                entity.Save();
                trans.Add(entity);
                //save promation lists

                SaveSaleListing(trans, entity);
                trans.Commit();
                return true;
            }
            catch (Exception)
            {
                trans.Rollback();

                throw;
            }
        }

        private void SaveSaleListing(Transaction trans, SaleEntity entity)
        {
            newItemArray = (GetItemArray());
            removedItemArray = new ItemIDArrayType();
            removedItemArray.ItemID = new StringCollection();
            ;

            if (Id > 0)
            {
                var saleListings = entity.SaleListings;
                foreach (var saleListing in saleListings)
                {
                    if (!newItemArray.ItemID.Contains(saleListing.ItemId))//removed
                    {
                        trans.Add(saleListing);
                        removedItemArray.ItemID.Add(saleListing.ItemId);
                        saleListing.Delete();

                    }
                    else
                    {
                        newItemArray.ItemID.Remove(saleListing.ItemId); //still exists ,removed from newItemArray
                    }
                }

            }
            foreach (string item in newItemArray.ItemID)
            {
                var newSaleListing = new SaleListingsEntity();
                newSaleListing.ItemId = item;
                newSaleListing.SaleId = entity.Id;
                trans.Add(newSaleListing);
                newSaleListing.Save();
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (CreateSale())
                {
                    if (Id > 0)
                    {
                        Success("Update sale successfully!");
                    }
                    else
                    {
                        Success("Create sale successfully!");
                    }
                    CloseWindow(true);
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message);

            }

        }
        protected void btnReload_Click(object sender, EventArgs e)
        {
            this.hyperLinkClearListings.Visible = this.fieldListingIds.Value.Trim().Length > 0;
        }


    }

}